package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exceptions.LeaseException;
import com.atguigu.lease.common.jwts.JwtUtil;
import com.atguigu.lease.common.redis.RedisConstant;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.mapper.SystemUserMapper;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SystemUserService systemUserService;

    @Autowired
    private SystemUserMapper systemUserMapper;

    @Override
    public CaptchaVo customCaptcha() {
        //3. 先生成验证码图片和正确验证码
        /*
            参数1：130 图片宽度 130像素
            参数2：48  图片宽度 48像素
            参数3 4    验证码长度
         */
        SpecCaptcha specCaptcha = new SpecCaptcha(130,48,4);
        //验证码的内容类型： 数字+字母
        specCaptcha.setCharType(Captcha.TYPE_DEFAULT);
        //获取验证码图片
        //todo: base64是一种转码和解码工具，可以将任何内容转成字符串
        //todo：1.怕乱吗的字符串，转成base64 2.非字符串想要在json中携带，可以转成base64
        String imageStr = specCaptcha.toBase64();
        //正确的验证码 1234
        String text = specCaptcha.text();

        //todo:引入一个常量类
        //定义：admin | app key的固定前缀
        //定义：超时时间类型的常量

        //4. 生成uuid
        String key = RedisConstant.ADMIN_LOGIN_PREFIX +  UUID.randomUUID().toString().replaceAll("-", "");

        //5. 将uuid + 正确验证码存储到redis[有效期]
        redisTemplate.opsForValue().set(key,text,RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);
        //6. 验证码图片和uuid Vocabulary返回 -> result.ok(vo)
        CaptchaVo captchaVo = new CaptchaVo(imageStr,key);
        return captchaVo;
    }

    @Override
    public String customLogin(LoginVo loginVo) {
        //1.验证码相关(验证码是否过期 | 验证码是否正确)
        String redisCode = (String) redisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        if (ObjectUtils.isEmpty(redisCode)){
            //验证码过期了
            //LeaseException
//            public LeaseException(ResultCodeEnum resultCodeEnum) {
//                super(resultCodeEnum.getMessage());
//                code = resultCodeEnum.getCode();
//            }
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        //有以避免空指针问题 用redisCode.equals()
        if (!redisCode.equalsIgnoreCase(loginVo.getCaptchaCode())){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        //2.检查账号
        LambdaQueryWrapper<SystemUser> systemUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        systemUserLambdaQueryWrapper.eq(SystemUser::getUsername,loginVo.getUsername());
        SystemUser systemUser = systemUserService.getOne(systemUserLambdaQueryWrapper);
        if (systemUser == null){
            //账号错误
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }
        //3.检查密码
        if (!systemUser.getPassword().equals(DigestUtils.md5Hex(loginVo.getPassword()))){
            //密码错误
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        //4.账号是否可用
        if (systemUser.getStatus() == BaseStatus.DISABLE){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
        //5.生成token

        String token = JwtUtil.createToken(systemUser.getId(), systemUser.getUsername());
        return token;

    }

    @Override
    public SystemUserInfoVo getLoginUserInfoById(Long userId) {
        SystemUser systemUser = systemUserMapper.selectById(userId);
        SystemUserInfoVo systemUserInfoVo = new SystemUserInfoVo();
        systemUserInfoVo.setName(systemUser.getName());
        systemUserInfoVo.setAvatarUrl(systemUser.getAvatarUrl());
        return systemUserInfoVo;
    }
}
